/*
 * Copyright (c) 2010-2011 NOO. All Rights Reserved.
 * [Id:DefRoleCmp.java  2011-11-04 下午8:58 poplar.yfyang ]
 */
package org.mumu.pawn.cmps.def;

import org.jboss.logging.Logger;
import org.joda.time.DateTimeUtils;
import org.mumu.pawn.beans.common.AccountSessionBean;
import org.mumu.pawn.cmps.RoleCmp;
import org.mumu.pawn.cmps.UserCmp;
import org.mumu.pawn.datamodal.EntityDataModalFactory;
import org.mumu.pawn.fm.dm.LazyPawnDataModel;
import org.mumu.pawn.domain.Role;
import org.mumu.pawn.model.Account;

import javax.inject.Inject;
import javax.persistence.EntityManager;

/**
 * <p>
 * .
 * </p>
 *
 * @author poplar.yfyang
 * @version 1.0 2011-11-04 下午8:58
 * @since JDK 1.5
 */
public class DefRoleCmp implements RoleCmp {
    private static final long serialVersionUID = 5094715728438118988L;

    @Inject
    private EntityManager entityManager;
    @Inject
    private Logger logger;

    @Inject
    private AccountSessionBean accountSessionBean;
    @Inject
    private UserCmp userCmp;

    @Override
    public void saveOrUpdateRole(Role role) {
        Account loginUser = accountSessionBean.getAccount();
        if (role.getId() == 0) {
            //new role
            role.setCreateActor(userCmp.getUser(loginUser.getId()));
            role.setCreateTime(DateTimeUtils.currentTimeMillis());
            entityManager.persist(role);
        } else {
            role.setUpdateActor(loginUser.getId());
            role.setUpdateTime(DateTimeUtils.currentTimeMillis());
            entityManager.merge(role);
        }
    }

    @Override
    public void deleteRole(long roleId) {
        Role role = findRole(roleId);
        entityManager.remove(role);
    }

    @Override
    public LazyPawnDataModel getRoleDataModal() {
        return EntityDataModalFactory.builderDataModal(entityManager,Role.class);
    }

    @Override
    public Role findRole(long roleId) {
        return entityManager.find(Role.class,roleId);
    }
}
